import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/BlankToolBarTool.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/RatingBar.dart';

class OrderCommentPage extends StatefulWidget {
  String id;
  OrderCommentPage({Key key, @required this.id}) : super(key: key);

  @override
  _OrderCommentPageState createState() => _OrderCommentPageState();
}

class _OrderCommentPageState extends State<OrderCommentPage> {
  String remark = "";
  double score = 0.0;
  String token = "";
  BlankToolBarModel barModel = BlankToolBarModel();
  List<Asset> images = new List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    barModel.outSideCallback = focusNodeChange;
    images.add(new Asset("","添加",30,30));
    getString(TOKEN).then((value) {
      token = value;
    });
  }

  void focusNodeChange() {
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> loadAssets() async {
    List<Asset> resultList;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 10 - images.length,
        enableCamera: true,
        materialOptions: MaterialOptions(
          actionBarTitle: "选择图片",
          allViewTitle: "已选择",
          actionBarColor: "#F1120D",
          actionBarTitleColor: "#ffffff",
          lightStatusBar: false,
          statusBarColor: "#F1120D",
          startInAllView: true,
          selectCircleStrokeColor: "#F1120D",
          selectionLimitReachedText: "已超出",
        ),
      );
    } on Exception catch (e) {
//      error = e.message;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    setState(() {
      if (resultList == null) {
        return;
      }
      for (int i = 0; i < resultList.length; i++) {
        images.insert(0, resultList[i]);
      }
      if (images.length >= 10) {
        images.removeAt(images.length - 1);
      }
//      if (error == null) _error = 'No Error Dectected';
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: new AppBar(
        title: new Text(
          "评价晒单",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: BlankToolBarTool.blankToolBarWidget(context,
          model: barModel,
          body: Container(
            child: new Column(
              children: <Widget>[
                Container(
                  padding:
                      EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_30)),
                  color: white,
                  child: new Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      ClipRRect(
                        borderRadius: BorderRadius.circular(5),
                        child: CachedNetworkImage(
                imageUrl:
                            'https://img14.360buyimg.com/n0/jfs/t1/42163/17/16172/246472/5d8dd42cE12fa785a/efbd7ce9dbaac1c1.jpg',
                            width: ScreenUtil.getInstance().setHeight(DP_120),
                            fit: BoxFit.fill,
                            height: ScreenUtil.getInstance().setHeight(DP_120)),
                      ),
                      Container(
                        width: ScreenUtil.getInstance().setHeight(DP_15),
                      ),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Expanded(
                                  child: Text('南京总统府(旧址)',
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(NORMAL_FONT_SIZE),
                                          color: Colors.black87)),
                                ),
                              ],
                            ),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Row(
                              children: <Widget>[
                                Text('礼盒装500ml',
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(SMALL_FONT_SIZE),
                                        color: Colors.black38)),
                              ],
                            ),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Text(MONEY + '234.99',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(BIG_FONT_SIZE),
                                    color: mainColor)),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Container(height: ScreenUtil.getInstance().setHeight(DP_20)),
                Container(
                  color: white,
                  padding:
                      EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_30)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Text('评分',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black)),
                          Container(
                            width: ScreenUtil.getInstance().setHeight(DP_30),
                          ),
                          RatingBar(
                            clickable: true,
                            size: ScreenUtil.getInstance().setHeight(DP_50),
                            color: mainColor,
                            padding: ScreenUtil.getInstance().setHeight(DP_10),
                            onValueChangedCallBack: (value) {
                              score = value;
                            },
                          ),
                        ],
                      ),
                      Container(
                        height: ScreenUtil.getInstance().setHeight(DP_30),
                      ),
                      Text('文字评论',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE),
                              color: black)),
                      TextField(
                        minLines: 4,
                        maxLines: 4,
                        onChanged: (value) {
                          remark = value;
                        },
                        cursorColor: mainColor,
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87),
                        decoration: InputDecoration(
                            hintText: '如果满意我们的产品，请给好评哦',
                            border: InputBorder.none,
                            hintStyle: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE),
                                color: Colors.black38)),
                      ),
                      Text('上传图片(选填)',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE),
                              color: black)),
                    ],
                  ),
                ),
                Expanded(
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.all(10.0),
                    color: white,
                    child: buildGridView(),
                  ),
                ),
                new Container(
                  width: double.infinity,
                  height: ScreenUtil.getInstance().setHeight(DP_80),
                  decoration: new BoxDecoration(
                      color: mainColor,
                      borderRadius: BorderRadius.circular(
                          ScreenUtil.getInstance().setHeight(DP_80))),
                  margin:
                      EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_60)),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "提交评价",
                        style: new TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      if (score <= 0) {
                        Fluttertoast.showToast(msg: "请给我们打个分吧");
                        return;
                      }
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (_) {
                            return new NetLoadingDialog(
                              loadingText: "提交中...",
                              bgColor: Color.fromARGB(255, 0, 0, 0),
                              requestCallBack: null,
                              outsideDismiss: false,
                            );
                          });
                      submit();
                    },
                  ),
                )
              ],
            ),
          )),
    );
  }

  submit() async {
    FormData formData = new FormData.fromMap({
      "token": token,
      "comment": remark,
      "id": widget.id,
      "point": score.toInt() * 2,
    });
    Response<String> response =
        await HttpUtil().post(Api.PUB_ORDER_COMMENT, data: formData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 0) {
      Navigator.pop(context);
    }
    return true;
  }

  void del(int index) {
    setState(() {
      if (images.length == 9 && images[8].name != '添加') {
        images.add(new Asset('images/img.png', "添加", 50, 50));
      }
      images.removeAt(index);
    });
  }

  Widget buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        if (asset.name == '添加') {
          return new GestureDetector(
            onTap: () {
              loadAssets();
            },
            child: Image.asset(
              'images/img.png',
              width: 50,
              height: 50,
              fit: BoxFit.cover,
            ),
          );
        }
        return Container(
          padding: EdgeInsets.all(5.0),
          height: 100,
          child: new Stack(
            alignment: AlignmentDirectional.topEnd,
            children: <Widget>[
              AssetThumb(
                asset: asset,
                width: 300,
                height: 300,
              ),
              new GestureDetector(
                onTap: () {
                  del(index);
                },
                child: Icon(
                  Icons.delete,
                  color: mainColor,
                ),
              )
            ],
          ),
        );
      }),
    );
  }
}
